package com.zycfc.zsf.boot.util.bean;

import java.io.*;

public abstract class Serializations
{
    public static Serializable copy(final Serializable obj) {
        if (obj == null) {
            return obj;
        }
        return deserialize(serialize(obj));
    }
    
    public static byte[] serialize(final Serializable s) {
        if (s == null) {
            return null;
        }
        try (final ByteArrayOutputStream bos = new ByteArrayOutputStream();
             final ObjectOutputStream oos = new ObjectOutputStream(bos)) {
            oos.writeObject(s);
            oos.flush();
            return bos.toByteArray();
        }
        catch (Exception e) {
            throw new RuntimeException("failed to serialize s: " + s, e);
        }
    }
    
    public static Serializable deserialize(final byte[] data) {
        if (data == null || data.length == 0) {
            return null;
        }
        return deserialize(data, 0, data.length);
    }
    
    public static Serializable deserialize(final byte[] data, final int offset, final int length) {
        if (data == null || data.length == 0) {
            return null;
        }
        try (final ByteArrayInputStream bis = new ByteArrayInputStream(data, offset, length);
             final ObjectInputStream ois = new ObjectInputStream(bis)) {
            return (Serializable)ois.readObject();
        }
        catch (Exception e) {
            throw new RuntimeException("failed to deserialize", e);
        }
    }
}
